import JSCookie from 'js-cookie'
import CryptoJS from 'crypto-js'

const KEY = {
  checkKey: 'isCheck',
  accountKey: 'account'
}
const secret = 'r738ifu35'

function isKey(key) {
  return key in KEY
}

function setCookie(key, value) {
  if (isKey(key)) {
    return JSCookie.set(key, value)
  }
}

function getCookie(key) {
  if (isKey(key)) {
    return JSCookie.get(key)
  }
}

function rmCookie(key) {
  if (isKey(key)) {
    return JSCookie.remove(key)
  }
}

function encryption(value) {
  return CryptoJS.AES.encrypt(value, secret).toString()
}

function decrypt(value) {
  return CryptoJS.AES.decrypt(value, secret)
}

export function isCheck() {
  return Boolean(getCookie('checkKey')) || false
}

export function setCheck() {
  setCookie('checkKey', true)
}

export function rmCheck() {
  rmCookie('checkKey')
}

export function setAccount({ username, password }) {
  const user = [username]
  user.push(encryption(password))
  setCookie('accountKey', user.join(','))
}

export function getAccount() {
  const res = getCookie('accountKey')
  if (res) {
    const user = res.split(',')
    const password = decrypt(user[1]).toString(CryptoJS.enc.Utf8)
    return {
      username: user[0],
      password
    }
  }
  return false
}

export function rmAccount() {
  rmCookie('accountKey')
}
